<!doctype html><html lang=zh-cn dir=ltr>
<head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1"><meta name=description content="闲来无事在网上翻一些关于 Javascript 的一些搞基技巧，就发现了节流与防抖这两种设计模式。
上个星期在编写搜索框的时候就已经写过类似的代码 （搜索框输入关键词会实时去服务器上搜索，考虑到服务器压力就把代码加了限制，每 500ms 最多搜索一次，实际上这就是类似防抖的设计，只是我还不知道这个叫防抖&amp;hellip;）
下面是搜索框的限制代码：
watch(searchText, (newVal) =&amp;gt; {  clearTimeout(searchTimer);  searchTimer = setTimeout(  () =&amp;gt; //...需要限制的逻辑  ),  500  ); }); 原理非常简单，通过定时器实现，一旦现有状态改变就说明有新的输入，然后清除老的定时器，新设置定时器。
 今天在网上冲浪又学到了一种新的设计：节流
直接看代码吧：
watch(searchText, (newVal) =&amp;gt; {   if(isStop) {  return  }   isStop = true;   setTimeout(  () =&amp;gt; {  //...需要限制的逻辑  isStop = false  }  ),  500 ); emmm，一开始看了半天，实际上看懂之后节流比防抖更加简单 （好吧，看了几遍其实发现差不多）"><title>节流与防抖</title><link rel=canonical href=https://sdttttt.github.io/blog/js-1/>
<link rel=stylesheet href=/scss/style.min.b80bf249ce4a22cf55e8d7340a0b37a2f2c10f54f3a9a49cb94b694a2eb0bbea.css><meta property="og:title" content="节流与防抖">
<meta property="og:description" content="闲来无事在网上翻一些关于 Javascript 的一些搞基技巧，就发现了节流与防抖这两种设计模式。
上个星期在编写搜索框的时候就已经写过类似的代码 （搜索框输入关键词会实时去服务器上搜索，考虑到服务器压力就把代码加了限制，每 500ms 最多搜索一次，实际上这就是类似防抖的设计，只是我还不知道这个叫防抖&amp;hellip;）
下面是搜索框的限制代码：
watch(searchText, (newVal) =&amp;gt; {  clearTimeout(searchTimer);  searchTimer = setTimeout(  () =&amp;gt; //...需要限制的逻辑  ),  500  ); }); 原理非常简单，通过定时器实现，一旦现有状态改变就说明有新的输入，然后清除老的定时器，新设置定时器。
 今天在网上冲浪又学到了一种新的设计：节流
直接看代码吧：
watch(searchText, (newVal) =&amp;gt; {   if(isStop) {  return  }   isStop = true;   setTimeout(  () =&amp;gt; {  //...需要限制的逻辑  isStop = false  }  ),  500 ); emmm，一开始看了半天，实际上看懂之后节流比防抖更加简单 （好吧，看了几遍其实发现差不多）">
<meta property="og:url" content="https://sdttttt.github.io/blog/js-1/">
<meta property="og:site_name" content="SDTTTTT">
<meta property="og:type" content="article"><meta property="article:section" content="Blog"><meta property="article:tag" content="Javascript"><meta property="article:published_time" content="2021-01-18T16:49:35+08:00"><meta property="article:modified_time" content="2021-01-18T17:07:10+08:00">
<meta name=twitter:title content="节流与防抖">
<meta name=twitter:description content="闲来无事在网上翻一些关于 Javascript 的一些搞基技巧，就发现了节流与防抖这两种设计模式。
上个星期在编写搜索框的时候就已经写过类似的代码 （搜索框输入关键词会实时去服务器上搜索，考虑到服务器压力就把代码加了限制，每 500ms 最多搜索一次，实际上这就是类似防抖的设计，只是我还不知道这个叫防抖&amp;hellip;）
下面是搜索框的限制代码：
watch(searchText, (newVal) =&amp;gt; {  clearTimeout(searchTimer);  searchTimer = setTimeout(  () =&amp;gt; //...需要限制的逻辑  ),  500  ); }); 原理非常简单，通过定时器实现，一旦现有状态改变就说明有新的输入，然后清除老的定时器，新设置定时器。
 今天在网上冲浪又学到了一种新的设计：节流
直接看代码吧：
watch(searchText, (newVal) =&amp;gt; {   if(isStop) {  return  }   isStop = true;   setTimeout(  () =&amp;gt; {  //...需要限制的逻辑  isStop = false  }  ),  500 ); emmm，一开始看了半天，实际上看懂之后节流比防抖更加简单 （好吧，看了几遍其实发现差不多）">
</head><body class=article-page>
<script>(function(){const e="StackColorScheme";localStorage.getItem(e)||localStorage.setItem(e,"auto")})()</script><script>(function(){const t="StackColorScheme",e=localStorage.getItem(t),n=window.matchMedia("(prefers-color-scheme: dark)").matches===!0;e=="dark"||e==="auto"&&n?document.documentElement.dataset.scheme="dark":document.documentElement.dataset.scheme="light"})()</script>
<div class="container main-container flex on-phone--column compact"><aside class="sidebar left-sidebar sticky">
<button class="hamburger hamburger--spin" type=button id=toggle-menu aria-label="Toggle Menu">
<span class=hamburger-box>
<span class=hamburger-inner></span>
</span>
</button>
<header>
<figure class=site-avatar>
<a href=/>
<img src=/img/avatar_hu8e30117ca872857dd9f41f234a693048_441529_300x0_resize_box_3.png width=300 height=300 class=site-logo loading=lazy alt=Avatar>
</a>
</figure><div class=site-meta>
<h1 class=site-name><a href=/>SDTTTTT</a></h1><h2 class=site-description>臭鱼烂虾</h2></div></header><ol class=menu id=main-menu>
<div class=menu-bottom-section>
<li id=dark-mode-toggle><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-toggle-left" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentcolor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z"/><circle cx="8" cy="12" r="2"/><rect x="2" y="6" width="20" height="12" rx="6"/></svg><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-toggle-right" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentcolor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z"/><circle cx="16" cy="12" r="2"/><rect x="2" y="6" width="20" height="12" rx="6"/></svg>
<span>Dark Mode</span>
</li></div></ol></aside><main class="main full-width">
<article class=main-article>
<header class=article-header>
<div class=article-details>
<div class=article-title-wrapper>
<h2 class=article-title>
<a href=/blog/js-1/>节流与防抖</a>
</h2></div><footer class=article-time>
<div><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-calendar-time" width="56" height="56" viewBox="0 0 24 24" stroke-width="2" stroke="currentcolor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z"/><path d="M11.795 21H5a2 2 0 01-2-2V7a2 2 0 012-2h12a2 2 0 012 2v4"/><circle cx="18" cy="18" r="4"/><path d="M15 3v4"/><path d="M7 3v4"/><path d="M3 11h16"/><path d="M18 16.496V18l1 1"/></svg>
<time class=article-time--published>Jan 18, 2021</time>
</div><div><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-clock" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentcolor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z"/><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 15"/></svg>
<time class=article-time--reading>
1 minute read
</time>
</div></footer></div></header><section class=article-content>
<p>闲来无事在网上翻一些关于 Javascript 的一些搞基技巧，就发现了节流与防抖这两种设计模式。</p><p>上个星期在编写搜索框的时候就已经写过类似的代码 <em>（搜索框输入关键词会实时去服务器上搜索，考虑到服务器压力就把代码加了限制，每 500ms 最多搜索一次，实际上这就是类似防抖的设计，只是我还不知道这个叫防抖&mldr;）</em></p><p>下面是搜索框的限制代码：</p><div class=highlight><pre tabindex=0 style=color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4><code class=language-javascript data-lang=javascript><span style=display:flex><span><span style=color:#a6e22e>watch</span>(<span style=color:#a6e22e>searchText</span>, (<span style=color:#a6e22e>newVal</span>) =&gt; {
</span></span><span style=display:flex><span>    <span style=color:#a6e22e>clearTimeout</span>(<span style=color:#a6e22e>searchTimer</span>);
</span></span><span style=display:flex><span>    <span style=color:#a6e22e>searchTimer</span> <span style=color:#f92672>=</span> <span style=color:#a6e22e>setTimeout</span>(
</span></span><span style=display:flex><span>        () =&gt; <span style=color:#75715e>//...需要限制的逻辑
</span></span></span><span style=display:flex><span><span style=color:#75715e></span>            ),
</span></span><span style=display:flex><span>        <span style=color:#ae81ff>500</span>
</span></span><span style=display:flex><span>    );
</span></span><span style=display:flex><span>});
</span></span></code></pre></div><p>原理非常简单，通过定时器实现，一旦现有状态改变就说明有新的输入，然后清除老的定时器，新设置定时器。</p><hr>
<p>今天在网上冲浪又学到了一种新的设计：<strong>节流</strong></p><p>直接看代码吧：</p><div class=highlight><pre tabindex=0 style=color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4><code class=language-javascript data-lang=javascript><span style=display:flex><span><span style=color:#a6e22e>watch</span>(<span style=color:#a6e22e>searchText</span>, (<span style=color:#a6e22e>newVal</span>) =&gt; {
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    <span style=color:#66d9ef>if</span>(<span style=color:#a6e22e>isStop</span>) {
</span></span><span style=display:flex><span>        <span style=color:#66d9ef>return</span>
</span></span><span style=display:flex><span>    }
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    <span style=color:#a6e22e>isStop</span> <span style=color:#f92672>=</span> <span style=color:#66d9ef>true</span>;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    <span style=color:#a6e22e>setTimeout</span>(
</span></span><span style=display:flex><span>        () =&gt; {
</span></span><span style=display:flex><span>            <span style=color:#75715e>//...需要限制的逻辑
</span></span></span><span style=display:flex><span><span style=color:#75715e></span>            <span style=color:#a6e22e>isStop</span> <span style=color:#f92672>=</span> <span style=color:#66d9ef>false</span>
</span></span><span style=display:flex><span>        }
</span></span><span style=display:flex><span>    ),
</span></span><span style=display:flex><span>    <span style=color:#ae81ff>500</span>
</span></span><span style=display:flex><span>);
</span></span></code></pre></div><p>emmm，一开始看了半天，实际上看懂之后节流比防抖更加简单 <em>（好吧，看了几遍其实发现差不多）</em></p><p>原理还是一样简单，计数器结束将标志位设置为 false，这样新来的计时器就能通过，如果没到限制时间就进入这个函数会被标志位拦住，直接返回。</p><p>节流主要作用就是限制执行频率。</p><p>硬要说防抖和节流的区别。。。emm我也说不上来，看应用场景吧。</p></section><footer class=article-footer>
<section class=article-tags>
<a href=/tags/javascript/>Javascript</a>
</section><section class=article-lastmod><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-clock" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentcolor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z"/><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 15"/></svg>
<span>
Last updated on Jan 18, 2021 17:07 CST
</span>
</section></footer></article><div id=gitalk-container></div><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/gitalk@1.7.2/dist/gitalk.css>
<script src=https://cdn.jsdelivr.net/npm/gitalk@1.7.2/dist/gitalk.min.js></script>
<script src=https://cdn.jsdelivr.net/npm/blueimp-md5@2.18.0/js/md5.min.js></script>
<script>const gitalk=new Gitalk({clientID:"97eb9ce8ac126f0c7833",clientSecret:"5da440441b500b0b016928640712a1b1a03a5f8f",repo:"sdttttt/sdttttt.github.io",owner:"sdttttt",admin:["sdttttt"],distractionFreeMode:!1,id:md5(location.pathname)});(function(){if(["localhost","127.0.0.1"].indexOf(window.location.hostname)!=-1){document.getElementById("gitalk-container").innerHTML="Gitalk comments not available by default when the website is previewed locally.";return}gitalk.render("gitalk-container")})()</script>
<footer class=site-footer>
<section class=copyright>
&copy;
2022 SDTTTTT
</section><section class=powerby>
Built with <a href=https://gohugo.io/ target=_blank rel=noopener>Hugo</a> <br>
Theme <b><a href=https://github.com/CaiJimmy/hugo-theme-stack target=_blank rel=noopener data-version=3.10.0>Stack</a></b> designed by <a href=https://jimmycai.com target=_blank rel=noopener>Jimmy</a>
</section></footer><div class=pswp tabindex=-1 role=dialog aria-hidden=true>
<div class=pswp__bg></div><div class=pswp__scroll-wrap>
<div class=pswp__container>
<div class=pswp__item></div><div class=pswp__item></div><div class=pswp__item></div></div><div class="pswp__ui pswp__ui--hidden">
<div class=pswp__top-bar>
<div class=pswp__counter></div><button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button class="pswp__button pswp__button--share" title=Share></button>
<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
<div class=pswp__preloader>
<div class=pswp__preloader__icn>
<div class=pswp__preloader__cut>
<div class=pswp__preloader__donut></div></div></div></div></div><div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
<div class=pswp__share-tooltip></div></div><button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
</button>
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
</button>
<div class=pswp__caption>
<div class=pswp__caption__center></div></div></div></div></div><script src=https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js integrity="sha256-ePwmChbbvXbsO02lbM3HoHbSHTHFAeChekF1xKJdleo=" crossorigin=anonymous defer></script><script src=https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js integrity="sha256-UKkzOn/w1mBxRmLLGrSeyB4e1xbrp4xylgAWb3M42pU=" crossorigin=anonymous defer></script><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css integrity="sha256-c0uckgykQ9v5k+IqViZOZKc47Jn7KQil4/MP3ySA3F8=" crossorigin=anonymous><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.css integrity="sha256-SBLU4vv6CA6lHsZ1XyTdhyjJxCjPif/TRkjnsyGAGnE=" crossorigin=anonymous>
</main></div><script src=https://cdn.jsdelivr.net/npm/node-vibrant@3.1.5/dist/vibrant.min.js integrity="sha256-5NovOZc4iwiAWTYIFiIM7DxKUXKWvpVEuMEPLzcm5/g=" crossorigin=anonymous></script><script type=text/javascript src=/ts/main.js defer></script>
<script>(function(){const e=document.createElement("link");e.href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700&display=swap",e.type="text/css",e.rel="stylesheet",document.head.appendChild(e)})()</script>
</body></html>